#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    int countNodes(TreeNode* root) {
        // 普通二叉树的遍历方法
        // if (root == nullptr) return 0;
        // return countNodes(root->left) + countNodes(root->right) + 1;

        if(root == nullptr) return 0;
        TreeNode * left = root->left;
        TreeNode * right = root->right;
        unsigned long leftDepth = 0, rightDepth = 0;
        while(left) {
            left = left->left;
            leftDepth++;
        }
        while(right){
            right = right->right;
            rightDepth++;
        }
        if (rightDepth == leftDepth){
            return 2 << rightDepth - 1;
        }

        return countNodes(root->left) + countNodes(root->right) + 1;
    }
};